import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: Andrey
 * Date: 08.04.13
 * Time: 19:56
 * To change this template use File | Settings | File Templates.
 */
public class Transleit
{
    static int numbers[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000, 4000};
    static String letters[] = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M", "MMMM"};
    static int last = 4000;

    public static void main(String[] args)
    {
        System.out.println("Ведите число римское или латинское (До МMMM или 3999): ");
        Scanner console = new Scanner(System.in);
        String value = console.next();

        try
        {
            char c = value.charAt(0);

            if ( Character.isDigit(c))
            {
                int int_value = Integer.parseInt(value);

                System.out.println("Римское значение = " + convertIntegerToRoman(int_value));
            }
            else
            {

                System.out.println("Латинское значение = " + convertRomanToInt(value));
            }
        }
        catch( NumberFormatException e)
        {
            System.out.println("Неправельно введено значение");
        }
    }

    public static int convertRomanToInt(String romanNumeral)
    {
        int integerValue = 0;

        for (int i = 0; i < romanNumeral.length(); i++)
        {
            char ch = romanNumeral.charAt(i);

            int number = letterToNumber(ch);

            if ( number == -1)
            {
                throw new NumberFormatException("Нету такого символа");
            }

            if (last<number)
                number-=last;
            integerValue += number;
            last = number;
        }

        return integerValue;
    }

    private static int letterToNumber(char letter)
    {

        switch (letter) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return -1;
        }
    }

    public static String convertIntegerToRoman(int number)
    {
        String romanValue = "";

        int N = number;

        while ( N > 0 )
        {
            for (int i = 0; i < numbers.length; i++)
            {
                if ( N < numbers[i] )
                {
                    N -= numbers[i-1];
                    romanValue += letters[i-1];
                    break;
                }
            }
        }
        return romanValue;
    }
}
